package cn.tedu.lbs.stock.web.service;

import cn.tedu.lbs.stock.web.repository.StockRepository;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tarena.lbs.base.common.utils.Asserts;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.pojo.stock.param.CouponStockParam;
import com.tarena.lbs.pojo.stock.po.CouponStockPO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class StockService {
    @Autowired
    private StockRepository stockRepository;

    public boolean initCouponStock(CouponStockParam param) {
        //param转化po
        CouponStockPO poParam = new CouponStockPO();
        BeanUtils.copyProperties(param,poParam);
        poParam.setCreateAt(new Date());
        poParam.setUpdateAt(new Date());
        //repository调用save写入数据库 insert 数据库返回 1 row affected 新增成功的
        return stockRepository.save(poParam);
    }

    public Integer getCouponStock(Integer couponId) throws BusinessException {
        //select num from coupon-stock where coupon_id=?
        QueryWrapper<CouponStockPO> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("coupon_id",couponId);
        CouponStockPO one = stockRepository.getOne(queryWrapper);
        Asserts.isTrue(one==null,new BusinessException("-2","优惠券库存不存在"));
        return one.getNum();
    }

    public boolean reduceCouponStock(Integer couponId, Integer num) {
        //扣减的数量num 不能超过库存剩余数量 外加一个where条件---乐观锁
        //update coupon_stock set num=num-? where coupon_id=? and num>=?
        int row=stockRepository.updateCouponStock(couponId,num);
        return row>0;
    }
}
